package net.pws.common.poi;

import java.io.FileInputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class PoiUtils {

	public static XWPFDocument replace(String templatePath,
			Map<String, CellOverrider> data) throws Exception {
		if (StringUtils.isBlank(templatePath) || data == null) {
			throw new IllegalArgumentException();
		}

		FileInputStream is = new FileInputStream(templatePath);
		CustomXWPFDocument document = new CustomXWPFDocument(is);
		int count = document.getTables().size();
		for (int a = 0; a < count; a++) {
			XWPFTable table = document.getTables().get(a);
			int rcount = table.getNumberOfRows();
			for (int i = 0; i < rcount; i++) {
				XWPFTableRow row = table.getRow(i);
				List<XWPFTableCell> cells = row.getTableCells();
				for (XWPFTableCell cell : cells) {
					String key = getReplaceKey(cell.getText());
					if (StringUtils.isNotEmpty(key) && data.containsKey(key)) {
						CellOverrider overrider = data.get(key);
						overrider.override(cell);
					}
				}

			}
		}

		return document;
	}

	private static String getReplaceKey(String text) {
		if (StringUtils.isBlank(text)) {
			return null;
		}
		text = text.trim();
		if (text.startsWith("{") && text.endsWith("}")) {
			return text.substring(1, text.length() - 1).trim();
		}
		return null;
	}
}
